package com.mvvm.store.ui.stockup;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.device.ScanManager;
import android.device.scanner.configuration.PropertyID;
import android.device.scanner.configuration.Triggering;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import androidx.viewpager.widget.ViewPager;

import com.leo.utilspro.utils.ToastUtils;
import com.mvvm.store.R;
import com.mvvm.store.base.BaseFragment;
import com.mvvm.store.base.NormalViewModel;
import com.mvvm.store.bean.basebean.MaterialInfoBean;
import com.mvvm.store.bean.basebean.ScanStockBean;
import com.mvvm.store.bean.basebean.StockUpInfoBean;
import com.mvvm.store.bean.basebean.StockUpScanInfoBean;
import com.mvvm.store.bean.basebean.UserAuthenticationBean;
import com.mvvm.store.customview.CustomProgress;
import com.mvvm.store.customview.iosdialog.DialogUtil;
import com.mvvm.store.databinding.FragmentStockSweptBinding;
import com.mvvm.store.roombatabase.ScanStockDao;
import com.mvvm.store.roombatabase.ScanStockDatabase;
import com.mvvm.store.roombatabase.StockUpInfoDao;
import com.mvvm.store.roombatabase.StockUpScanDao;
import com.mvvm.store.roombatabase.StockUpScanDatabase;
import com.mvvm.store.roombatabase.StoreHouseDatabase;
import com.mvvm.store.ui.stockup.adapter.StockSweptAdapter;
import com.mvvm.store.utils.StringUtils;

import java.util.ArrayList;
import java.util.List;

import static android.content.Context.MODE_PRIVATE;


/**
 * Created by leo
 * on 2020/10/21.   备货物料扫码界面
 */
public class StockUpSweptFragment extends BaseFragment<StockUpViewModel, FragmentStockSweptBinding> {

    int index;
    private StockSweptAdapter sweptAdapter;
    private int curPage = 0;
    private ArrayList<StockUpScanInfoBean> stockUpScanInfoBeansListToAdaper = new ArrayList<>();
    private CustomProgress dialog;
    private  StockUpScanDao stockUpScanDao;
    private StockUpInfoDao stockUpInfoDao;
    private String orderId;
    private ScanStockDao scanStockDao;

    //到时候这里用来传值
    public static StockUpSweptFragment newInstance(final String name, ViewPager viewPager) {
        StockUpSweptFragment mFragment = new StockUpSweptFragment();
        Bundle bundle = new Bundle();
        bundle.putString("name", name);
        mFragment.setArguments(bundle);
        return mFragment;
    }

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_stock_swept;
    }

    @Override
    protected void processLogic(Bundle savedInstanceState) {

        //Sp获取点击备货列表数据的订单号的值
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("stockInfo", MODE_PRIVATE);
        orderId=sharedPreferences.getString("orderId","");
        System.out.println("备货扫码--------------orderId---------备货-----------"+orderId);

        if(dialog==null) {
            dialog = CustomProgress.show(getActivity(), "", true, null);
        }
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    Thread.sleep(500);//休眠3秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                /**
                 * 要执行的操作
                 */
                dialog.dismiss();
            }
        }.start();
        stockUpScanDao=StockUpScanDatabase.getInstance(getActivity()).stockUpScanDao();
        stockUpInfoDao=StoreHouseDatabase.getInstance(getActivity()).stockUpDao();
        scanStockDao= ScanStockDatabase.getInstance(getActivity()).scanStockDao();
        binding.includeEmpty.setTextEmpty("瞅啥，没有你的收藏~");
        binding.includeEmpty.setImageEmpty(R.mipmap.no_data);

        //先查询本地数据是否有对应的扫码数据
        List<StockUpScanInfoBean> stockUpScanInfoBeans=stockUpScanDao.getAll(orderId);
        binding.tvStockSupplierName.setText(stockUpScanInfoBeans.size()+"");
        if(stockUpScanInfoBeans.size()>0){
            binding.includeEmpty.relativeNull.setVisibility(View.GONE);
            for (int i=0;i<stockUpScanInfoBeans.size();i++){
                stockUpScanInfoBeansListToAdaper.add(stockUpScanInfoBeans.get(i));
            }
        }else {
            binding.includeEmpty.relativeNull.setVisibility(View.VISIBLE);
        }

        sweptAdapter=new StockSweptAdapter();
        sweptAdapter.setDataList(stockUpScanInfoBeansListToAdaper);
        binding.recyclerView.setAdapter(sweptAdapter);


        sweptAdapter.setOnclick(new StockSweptAdapter.ClickInterface() {
            @Override
            public void onImagesClick(View view, int position, StockUpScanInfoBean materialInfoBean) {
                stockUpScanInfoBeansListToAdaper.remove(position);
                sweptAdapter.notifyDataSetChanged();
            }

            @Override
            public void onItemClick(View view, int position, StockUpScanInfoBean materialInfoBean) {

            }
        });
    }


    @Override
    protected void setListener() {
        ButtonListener listener = new ButtonListener();
        binding.llScan.setOnTouchListener(listener);
        binding.llScan.setOnClickListener(listener);
    }

    @Override
    public void onClick(View v) {
    }

    /**
     * Button helper
     */
    class ButtonListener implements View.OnClickListener, View.OnTouchListener {
        public void onClick(View v) {
            System.out.println("ButtonListener onClick");
        }

        public boolean onTouch(View v, MotionEvent event) {
            if (v.getId() == R.id.ll_scan) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    binding.tvScanDes.setText("请扫描物料标签");
                    if (getTriggerMode() == Triggering.HOST) {
                        stopDecode();
                    }
                }
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    binding.tvScanDes.setText("松开完成");
                    startDecode();
                }
            }
            return false;
        }

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(hidden){
            System.out.println("MaterialSweptFragment----hidden");
        }else {
            System.out.println("MaterialSweptFragment------no----hidden");
        }
    }
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            //TODO 刷新数据方法在这里调用
            System.out.println("MaterialSweptFragment-----8888888899999999999999999999");
            if(sweptAdapter!=null){
                stockUpScanInfoBeansListToAdaper.clear();
                //先查询本地数据是否有对应的扫码数据
                List<StockUpScanInfoBean> stockUpScanInfoBeans=stockUpScanDao.getAll(orderId);
                binding.tvStockSupplierName.setText(stockUpScanInfoBeans.size()+"");
                System.out.println("MaterialSweptFragment-----888888888888888"+stockUpScanInfoBeans.size());
                for (int i=0;i<stockUpScanInfoBeans.size();i++){
                    stockUpScanInfoBeansListToAdaper.add(stockUpScanInfoBeans.get(i));
                }
                sweptAdapter.notifyDataSetChanged();
            }
        }
    }
    //--------------------------------------------------------------------------------------------------------------------------------
    private static final String ACTION_DECODE = ScanManager.ACTION_DECODE;   // default action
    private static final String ACTION_DECODE_IMAGE_REQUEST = "action.scanner_capture_image";
    private static final String ACTION_CAPTURE_IMAGE = "scanner_capture_image_result";
    private static final String BARCODE_STRING_TAG = ScanManager.BARCODE_STRING_TAG;
    private static final String BARCODE_TYPE_TAG = ScanManager.BARCODE_TYPE_TAG;
    private static final String BARCODE_LENGTH_TAG = ScanManager.BARCODE_LENGTH_TAG;
    private static final String DECODE_DATA_TAG = ScanManager.DECODE_DATA_TAG;
    private static final String DECODE_CAPTURE_IMAGE_KEY = "bitmapBytes";
    private ScanManager mScanManager = null;
    private static boolean mScanEnable = true;
    private static boolean mScanCaptureImageShow = false;
    private static final int MSG_SHOW_SCAN_RESULT = 1;
    private static final int MSG_SHOW_SCAN_IMAGE = 2;
    private static final int[] SCAN_KEYCODE = {520, 521, 522, 523};

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            System.out.println("onReceive , action:" + action);
            // Get Scan Image . Make sure to make a request before getting a scanned image
            if (ACTION_CAPTURE_IMAGE.equals(action)) {
                byte[] imagedata = intent.getByteArrayExtra(DECODE_CAPTURE_IMAGE_KEY);
                if (imagedata != null && imagedata.length > 0) {
                    Bitmap bitmap = BitmapFactory.decodeByteArray(imagedata, 0, imagedata.length);
                    Message msg = mHandler.obtainMessage(MSG_SHOW_SCAN_IMAGE);
                    msg.obj = bitmap;
                    mHandler.sendMessage(msg);
                } else {
                    System.out.println("onReceive , ignore imagedata:" + imagedata);
                }
            } else {
                // Get scan results, including string and byte data etc.
                byte[] barcode = intent.getByteArrayExtra(DECODE_DATA_TAG);
                int barcodeLen = intent.getIntExtra(BARCODE_LENGTH_TAG, 0);
                byte temp = intent.getByteExtra(BARCODE_TYPE_TAG, (byte) 0);
                String barcodeStr = intent.getStringExtra(BARCODE_STRING_TAG);
                if (mScanCaptureImageShow) {
                    // Request images of this scan
                    context.sendBroadcast(new Intent(ACTION_DECODE_IMAGE_REQUEST));
                }
                System.out.println("barcode type:" + temp);
                String scanResult = new String(barcode, 0, barcodeLen);
                // print scan results.
                scanResult = " length：" + barcodeLen + "\nbarcode：" + scanResult + "\nbytesToHexString：" + bytesToHexString(barcode) + "\nbarcodeStr:" + barcodeStr;
                Message msg = mHandler.obtainMessage(MSG_SHOW_SCAN_RESULT);
                msg.obj = barcodeStr;
                mHandler.sendMessage(msg);
            }
        }
    };

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SHOW_SCAN_RESULT:
                    String scanResult = (String) msg.obj;
                    System.out.println("scanResult"+scanResult);
                    printScanResult(scanResult);
                    break;
            }
        }
    };
    /**
     * @param register , ture register , false unregister
     */
    private void registerReceiver(boolean register) {
        if (register && mScanManager != null) {
            IntentFilter filter = new IntentFilter();
            int[] idbuf = new int[]{PropertyID.WEDGE_INTENT_ACTION_NAME, PropertyID.WEDGE_INTENT_DATA_STRING_TAG};
            String[] value_buf = mScanManager.getParameterString(idbuf);
            if (value_buf != null && value_buf[0] != null && !value_buf[0].equals("")) {
                filter.addAction(value_buf[0]);
            } else {
                filter.addAction(ACTION_DECODE);
            }
            filter.addAction(ACTION_CAPTURE_IMAGE);

            getActivity().registerReceiver(mReceiver, filter);
        } else if (mScanManager != null) {
            mScanManager.stopDecode();
            getActivity().unregisterReceiver(mReceiver);
        }
    }

    /**
     * byte[] toHex String
     *
     * @param src
     * @return String
     */
    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    /**
     * Intent Output Mode print scan results.
     *
     * @param msg
     */
    private void printScanResult(String msg) {
        if (msg == null) {
            System.out.println("printScanResult , ignore to show msg:" + msg + ",showScanResult");
            return;
        }
        //------------------------------------------------------------------------------------------
        binding.includeEmpty.relativeNull.setVisibility(View.GONE);
        //获取到扫码结果后的处理
        System.out.println("msg"+msg);

        //提交时处理扫码
        DialogUtil.dismissDialog();
        if(StockUpActivity.isStockUpSubmitScan){

            DialogUtil.alertIosDialog(getActivity(), "   你的身份信息为："+msg+"请核对后点击确认", "确定", "取消", new DialogUtil.DialogAlertListener() {
                @Override
                public void yes() {
                    //调用接口验证身份。
                    UserAuthenticationBean userAuthenticationBean=new UserAuthenticationBean();
                    userAuthenticationBean.setStockOrderNo(orderId);
                    userAuthenticationBean.setUserId(msg);
                    mViewModel.userAuthentication(userAuthenticationBean).observe(getActivity(),resourse->resourse.handler(new OnCallback<String>() {
                        @Override
                        public void onSuccess(String data) {
                            if("true".equals(data)){
                                ToastUtils.showToast("身份验证成功,请继续提交");
                                SharedPreferences sharedPreferences = getActivity().getSharedPreferences("stockUpUserInfo", MODE_PRIVATE);
                                SharedPreferences.Editor editor = sharedPreferences.edit();
                                editor.putString("stockUpUserId", msg);
                                editor.commit();

                            } else {
                                ToastUtils.showToast("身份验证失败,请核对后再次验证");
                            }
                        }
                    }));


                }
            });
        }

        else {
            //获取扫码的值进行截取赋值
            //先判断是否为空
            if (!TextUtils.isEmpty(msg)) {
                //判断是否包含我们格式的字符串
                int isTrue = StringUtils.countStr(msg, "-");
                System.out.println("isTrue" + isTrue);
                StringUtils.setCounter(0);
                if (isTrue == 3) {
                    List<ScanStockBean>  scanStockBeanList= scanStockDao.getScanStockBeanByLableNumber(msg);
                    if(scanStockBeanList.size()>0) {
                        //进行截取获取
                        String[] codeString = msg.split("-");
                        System.out.println(codeString[1].toString());
                        //去除字符串前面的0
                        String newStrPackage = codeString[1].replaceAll("^(0+)", ""); //箱数
                        System.out.println("截取后的每箱数量的值" + newStrPackage);
                        String oddNumber = codeString[0]; //零件号
                        System.out.println("截取后的零件号的值" + oddNumber);
                        String dateTime = codeString[2]; //扫码获取时间字段
                        String packageNumber = codeString[3]; //扫码获取的箱数编号
                        //插入之前先判断用户是否扫了同一个标签，根据标签查询
                        List<StockUpScanInfoBean> stockUpInfoBeanList = stockUpScanDao.getStockUpInfoByLableNumber(msg);
                        if (stockUpInfoBeanList.size() > 0) {
                            System.out.println("查询扫码表对应的已有的数据" + stockUpInfoBeanList.get(0).toString());
                            Toast.makeText(getActivity(), "亲，该标签已经被扫过了,请勿多次扫描", Toast.LENGTH_SHORT).show();
                        } else {
                            //查询订单表对应的数据零件号查询
                            List<StockUpInfoBean> stockUpInfoBeans = stockUpInfoDao.getStockUpInfoByOddNumber(oddNumber);
                            if (stockUpInfoBeans.size() > 0) {

                                System.out.println("查询订单表对应的零件号" + stockUpInfoBeans.get(0).toString());
                                //订单表有零件号对应的数据进行累加
                                for (int i = 0; i < stockUpInfoBeans.size(); i++) {
                                    //先判断 扫码箱数及数量是否和订单数量一致了。
                                    StockUpInfoBean stockUpInfoBean = stockUpInfoBeans.get(i);
                                    //累加数量
                                    int realNumber = stockUpInfoBean.getRealToNumber();
                                    System.out.println("需要的数量" + stockUpInfoBean.getSumNumber() + "扫码的数量" + realNumber);
                                    if (realNumber >= stockUpInfoBean.getSumNumber()) {
                                        Toast.makeText(getActivity(), "当前订单备货已完成", Toast.LENGTH_SHORT).show();
                                    } else {
                                        int addRealNumber = realNumber + Integer.parseInt(newStrPackage);
                                        stockUpInfoBean.setRealToNumber(addRealNumber);
                                        //累加箱数
                                        int packageNumbers = stockUpInfoBean.getRealToPack();
                                        int addPackageNumber = packageNumbers + 1;
                                        stockUpInfoBean.setRealToPack(addPackageNumber);
                                        stockUpInfoDao.updateStudent(stockUpInfoBean);
                                        //插入数据到已扫物料标签
                                        List<StockUpScanInfoBean> stockUpScanInfoBeansToload = stockUpScanDao.getStockUpInfoByLableNumber(msg);
                                        if (stockUpScanInfoBeansToload.size() > 0) {
                                            System.out.println("备货本地有数据了");
                                        } else {
                                            StockUpScanInfoBean stockUpScanInfoBean = new StockUpScanInfoBean();
                                            stockUpScanInfoBean.setLableNumber(msg);
                                            stockUpScanInfoBean.setOrderNumber(orderId);
                                            stockUpScanInfoBean.setOddNumber(oddNumber);
                                            stockUpScanInfoBean.setSumNumber(newStrPackage);
                                            stockUpScanInfoBean.setDateTime(dateTime);
                                            stockUpScanInfoBean.setSnpNumber(newStrPackage);
                                            stockUpScanInfoBean.setPackNumber(packageNumber);
                                            stockUpScanDao.insertAll(stockUpScanInfoBean);
                                            //  刷新适配器数据
                                            stockUpScanInfoBeansListToAdaper.add(stockUpScanInfoBean);
                                        }
                                        sweptAdapter.notifyDataSetChanged();
                                        binding.recyclerView.smoothScrollToPosition(stockUpScanInfoBeansListToAdaper.size());
                                        binding.tvStockSupplierName.setText(stockUpScanDao.getAll(orderId).size() + "");
                                    }
                                }

                            } else {
                                //扫描的标签没有对应的零件号
                                Toast.makeText(getActivity(), "扫码的零件号订单没有对应记录,请重新扫码", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }else {
                        ToastUtils.showToast("备货标签与返回的标签不匹配！");
                    }
                    //else-------


                } else {
                    Toast.makeText(getActivity(), "扫码获取的格式不正确", Toast.LENGTH_SHORT).show();
                }

            } else {
                Toast.makeText(getActivity(), "扫码未获取结果", Toast.LENGTH_SHORT).show();
            }
        }

    }
    private void initScan() {
        mScanManager = new ScanManager();
        mScanManager.switchOutputMode(0);
        boolean powerOn = mScanManager.getScannerState();
        if (!powerOn) {
            powerOn = mScanManager.openScanner();
            if (!powerOn) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setMessage("Scanner cannot be turned on!");
                builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                AlertDialog mAlertDialog = builder.create();
                mAlertDialog.show();
            }
        }
    }

    /**
     * ScanManager.getTriggerMode
     *
     * @return
     */
    private Triggering getTriggerMode() {
        Triggering mode = mScanManager.getTriggerMode();
        return mode;
    }

    /**
     * ScanManager.getTriggerLockState
     *
     * @return
     */
    private boolean getlockTriggerState() {
        boolean state = mScanManager.getTriggerLockState();
        return state;
    }

    /**
     * ScanManager.startDecode
     */
    private void startDecode() {
        if (!mScanEnable) {
            System.out.println("startDecode ignore, Scan enable:" + mScanEnable);
            return;
        }
        boolean lockState = getlockTriggerState();
        if (lockState) {
            System.out.println("startDecode ignore, Scan lockTrigger state:" + lockState);
            return;
        }
        if (mScanManager != null) {
            mScanManager.startDecode();
        }
    }

    /**
     * ScanManager.stopDecode
     */
    private void stopDecode() {
        if (!mScanEnable) {
            System.out.println("stopDecode ignore, Scan enable:" + mScanEnable);
            return;
        }
        if (mScanManager != null) {
            mScanManager.stopDecode();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        System.out.println("onPauseonPauseonPause");
        registerReceiver(false);
    }

    @Override
    public void onResume() {
        super.onResume();
        initScan();
        registerReceiver(true);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
